<?php

use Illuminate\Database\Seeder;
use Laravel\Passport\Client;
use Carbon\Carbon;
use App\Models\AdminPermission;
use App\Models\Permission;
use App\Models\Role;
use App\Models\Menu;
use App\Models\Admin;


class AdminTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //清空表
        $this->truncateTable();

        //执行迁移，生成默认管理员，自带的菜单
        \Artisan::call('admin:install');

        //添加权限
        $this->createPermission();

        //添加默认角色
//        $this->createRole();

        //添加默认菜单
        $this->createMenu();

        //添加后台账号
//        $this->createAdministrator();

        //添加 OAUTH_CLIENT_ID
//        if (Client::count() == 0)
//        {
//            \Artisan::call("passport:install");
//        }
    }

    private function createPermission()
    {
        //后端权限
        foreach (AdminPermission::$defaults as $slug => $value)
        {
            $httpBasePath = sprintf("%s", trim($value['http_path'], '/'));
            $httpPath = sprintf("/%s", $httpBasePath);
            AdminPermission::create([
                'slug' => $slug,
                'name' => $value['name'],
                'http_path' => $httpPath,
            ]);
        }
        //前端权限
        foreach (Permission::$defaults as $slug => $value)
        {
            Permission::firstOrCreate([
                'slug' => $slug,
                'name' => $value['name'],
            ]);
        }

    }

    /**
     * 创建角色，注意这里是前端员工的角色，后台管理员没有角色
     */
    private function createRole()
    {
        foreach (Role::$defaults as $slug => $value)
        {
            $role = Role::firstOrCreate([
                'name' => $value['name'],
                'slug' => $slug,
            ]);
            if (!empty($value['permissions']))
            {
                $permissions = AdminPermission::whereIn("slug", $value['permissions'])->get();
                $role->permissions()->saveMany($permissions);
            }
        }


    }

    private function createMenu()
    {
        $order = Menu::max('order');
        $order = $this->doCreateMenu(Menu::$defaults, 0, $order);
        //把系统放到最下边
        $adminMenu = Menu::find(2);
        if ($adminMenu)
        {
            $adminMenu->order = $order;
            $adminMenu->save();
        }
    }

    private function doCreateMenu($menus, $parentId = 0, $order = 1)
    {
        foreach ($menus as $item)
        {
            $menu = Menu::create([
                'parent_id' => $parentId,
                'title' => $item['title'],
                'icon' => $item['icon'],
                'uri' => trim($item['uri'], '/'),
                'order' => $order,
            ]);
            $order++;
            if (!empty($item['roles'])) {
                $rolesToBind = Role::whereIn("slug", $item['roles'])->get();
                $menu->roles()->saveMany($rolesToBind);
            }
            if (!empty($item['children'])) {
                $order = $this->doCreateMenu($item['children'], \Db::getPdo()->lastInsertId(), $order);
            }
        }
        return $order;
    }

    private function createAdministrator()
    {
        foreach (Role::$defaults as $slug => $value)
        {
            //每种角色的创建一个
            $admin = Admin::create([
                'username' => $slug,
                'password' => bcrypt($slug),
                'name' => $value['name'],
            ]);
            $admin->roles()->save(Role::where("slug", $slug)->first());
        }

    }

    private function truncateTable()
    {
        $tables = config('admin.database');
        foreach ($tables as $key => $value)
        {
            if (strpos($key, "_table") !== false)
            {
                \DB::table($value)->truncate();
            }
        }
    }

}
